<template>
  <div class="filepreview-container">
    <!-- 默认展示区域 -->
    <div class="file-box" @click="openPreviewDialog">
      <FileDisplay
        :file-src="currentFile.src"
        :file-name="currentFile.name"
        :file-type="currentFile.filetype"
        :active-sheet-name="activeSheetName"
        :xls-data="xlsData"
        :txt-data="txtData"
        @sheet-change="handleSheetChange"
      />
    </div>

    <!-- 预览对话框 -->
    <PreviewDialog
      :show-dialog="showPreviewDialog"
      :file-list="fileList"
      :initial-src="props.src"
      @close="closePreviewDialog"
    />
  </div>
</template>

<script setup name="FilePreview">
import { ref, computed, defineProps, watch } from "vue"
import FileDisplay from "./FileDisplay.vue"
import PreviewDialog from "./PreviewDialog.vue"
import { processFileList, generateCurrentFile, getFileArrayBufferBySrc } from "./fileUtils"
import * as XLSX from "xlsx-js-style"

/**
 * 组件属性定义
 */
const props = defineProps({
  // 当前显示的文件路径
  src: {
    type: String,
    required: true
  },
  // 文件列表（点击后预览的文件列表）
  srcList: {
    type: Array,
    default: () => []
  }
})

// 响应式数据
const showPreviewDialog = ref(false)
const activeSheetName = ref(undefined)
const xlsData = ref({})
const txtData = ref(undefined)

/**
 * 处理文件列表，根据URL或对象生成统一的文件列表格式
 */
const fileList = computed(() => {
  return processFileList(props.srcList, props.src)
})

/**
 * 当前显示的文件（默认显示区域使用）
 */
const currentFile = computed(() => {
  return generateCurrentFile(props.src)
})

/**
 * 加载默认展示文件的数据（仅处理需要特殊处理的文件类型）
 */
const loadDefaultFileData = async () => {
  const file = currentFile.value
  if (!file || !file.src) return

  // 重置数据
  activeSheetName.value = undefined
  xlsData.value = {}
  txtData.value = undefined

  try {
    // 处理Excel文件(.xls)
    if (file.filetype === "xls") {
      const arrayBuffer = await getFileArrayBufferBySrc(file.src, false)
      const data = new Uint8Array(arrayBuffer)
      const workbook = XLSX.read(data, { type: "buffer" })
      activeSheetName.value = workbook.SheetNames[0]
      workbook.SheetNames.forEach(sheetName => {
        const worksheet = workbook.Sheets[sheetName]
        xlsData.value[sheetName] = XLSX.utils.sheet_to_json(worksheet)
      })
    }
    // 处理文本文件(.txt)
    else if (file.filetype === "txt") {
      const arrayBuffer = await getFileArrayBufferBySrc(file.src, false)
      const decoder = new TextDecoder("utf-8")
      txtData.value = decoder.decode(arrayBuffer)
    }
  } catch (error) {
    console.error("加载文件失败:", error)
  }
}

/**
 * 监听src变化，加载文件数据
 */
watch(
  () => props.src,
  () => {
    loadDefaultFileData()
  },
  { immediate: true }
)

/**
 * 打开预览对话框
 */
const openPreviewDialog = () => {
  if (fileList.value.length === 0 || !currentFile.value.src) return
  showPreviewDialog.value = true
}

/**
 * 关闭预览对话框
 */
const closePreviewDialog = () => {
  showPreviewDialog.value = false
}

/**
 * 处理Excel工作表切换
 * @param {string} sheetName - 工作表名称
 */
const handleSheetChange = sheetName => {
  activeSheetName.value = sheetName
}
</script>

<style lang="scss" scoped>
.filepreview-container {
  width: 100%;
  position: relative;

  .file-box {
    width: 100%;
    height: 400px;
    cursor: pointer;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    overflow: hidden;

    &:hover {
      border-color: #409eff;
    }
  }
}
</style>